package com.mls.fivedistrict.controller.backend;

import com.github.pagehelper.PageInfo;
import com.mls.fivedistrict.common.ServiceResponse;
import com.mls.fivedistrict.controller.BaseController;
import com.mls.fivedistrict.exception.CustomerException;
import com.mls.fivedistrict.pojo.Paradrop;
import com.mls.fivedistrict.server.ParadropServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * Created by chenxiuxiang on 2018/4/16.
 */
@RestController
@RequestMapping("/api/manager")
public class ParadropController extends BaseController {
    @Autowired
    ParadropServer paradropServer;

    @PostMapping("/v1/paradrop")
    public ServiceResponse addParadrop(@RequestBody Paradrop paradrop) {
        int i = paradropServer.addParadrop(paradrop);
        if (i > 0) {
            return ServiceResponse.createSuccessResponse();
        } else {
            return ServiceResponse.createErrorResponse("添加失败");
        }
    }

    @PutMapping("/v1/paradrop/{paradropId}")
    public ServiceResponse editParadrop(@PathVariable Long paradropId, @RequestBody Paradrop paradrop) {
        paradrop.setId(paradropId);
        int i = paradropServer.editParadrop(paradrop);
        if (i > 0) {
            return ServiceResponse.createSuccessResponse();
        } else {
            return ServiceResponse.createErrorResponse("编辑失败");
        }
    }

    @DeleteMapping("/v1/paradrop/{paradropId}")
    public ServiceResponse deleteParadrop(@PathVariable Long paradropId) {
        int i = paradropServer.deleteParadrop(paradropId);
        if (i > 0) {
            return ServiceResponse.createSuccessResponse();
        } else {
            return ServiceResponse.createErrorResponse("删除失败");
        }
    }

    @GetMapping("/v1/paradrops")
    public ServiceResponse getParadropList() {
        List<Paradrop> paradropList = paradropServer.getParadropList(getPageFilter());
        PageInfo pageInfo = new PageInfo(paradropList, 5);
        return ServiceResponse.createSuccessResponse(pageInfo);
    }

    @GetMapping("/v1/paradrop/{paradropId}")
    public ServiceResponse getParadrop(@PathVariable Long paradropId) {
        Paradrop paradrop = paradropServer.getParadropDetail(paradropId);
        if (paradrop != null) {
            return ServiceResponse.createSuccessResponse(paradrop);
        } else {
            return ServiceResponse.createErrorResponse("空投不存在");
        }
    }

    @PostMapping("/v1/paradrop/execute")
    public ServiceResponse executeParadrop(@RequestBody Paradrop paradrop) {
        Optional.ofNullable(paradrop.getId()).orElseThrow(() -> new CustomerException("空投计划不存在"));
        int i = paradropServer.startParadrop(paradrop.getId());
        if (i > 0) {
            return ServiceResponse.createSuccessResponse();
        } else {
            return ServiceResponse.createErrorResponse("执行失败");
        }
    }

}
